import {simplePost} from "@/utils/request";
import {ElMessageBox, ElLoading, FormInstance} from 'element-plus'
import List from "@/model/list";
import {msgError, msgSuccess} from "@/utils/alert";

export default class Edit {

    show: boolean;

    loading: boolean;

    info: any;

    constructor({show = false, loading = false, info = {}}: { show?: boolean, loading?: boolean, info?: any }) {
        this.show = show
        this.loading = loading
        this.info = info
    }

    async init(callback: Function){
        this.loading = true
        await callback(this)
        this.loading = false
    }

    submit({
               formRef,
               url,
               list,
               data,
           }: { formRef?: FormInstance, url: string, list?: List, data?:any }) {

        return new Promise(resolve => {
            if (!formRef) {
                msgError("无法获取表单对象")
                return
            }

            formRef.validate((valid, fields) => {
                if (valid) {
                    this.loading = true
                    const post = data || this.info
                    try {
                        simplePost(url, post).then((res:any) => {
                            msgSuccess("保存成功")
                            if (list) {
                                // 刷新列表
                                list.reload()
                            }
                            // 关闭弹窗
                            this.show = false
                            resolve(res)
                        })
                    } catch (e) {

                    }finally {
                        // 停止加载
                        this.loading = false
                    }

                } else {
                    for (let prop in fields) {
                        formRef.scrollToField(prop)
                        break
                    }
                }
            }).then(r => {
            })

        })



    }

}
